//
//  CommunityViewController.m
//  1gene
//
//  Created by 1jiyin on 16/2/26.
//  Copyright © 2016年 1jiyin. All rights reserved.
//
//***************************社区***************************
#import "CommunityViewController.h"
#import "HotAndGreatViewController.h"
#import "HuDongViewController.h"
#import "MessageListViewController.h"
#import "ShowDaySignInViewController.h"
#import "ZGWHuDongViewController.h"


@interface CommunityViewController ()<CommunityTableViewDelegate>
/**
 *定时器
 */
@property(nonatomic,copy)NSTimer *myTimer;
@property(nonatomic,assign)NSInteger myTime;

@property(nonatomic,assign)BOOL gotoShowDaySignInViewController;

@end

@implementation CommunityViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor colorWithRed:235/255.0 green:235/255.0 blue:241/255.0 alpha:1];
    [self.view addSubview:[UIView new]];
    //隐藏navigationBar
    self.navigationController.navigationBar.hidden=YES;
    
    self.navigationController.navigationBar.barStyle=UIBarStyleBlack;
    NSLog(@"社区");
    
    [self createUI];
    
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(addUserSuccess) name:@"careUserSuccessMessage" object:nil];
    // Do any additional setup after loading the view.
}

//关注成功
-(void)addUserSuccess
{
    [self.view showTiShiMessage:@"关注成功"];
}
-(void)createUI
{
    CommunityTableView *table=[[CommunityTableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-10) style:UITableViewStyleGrouped];
    table.myDelegate=self;
    table.backgroundColor=[UIColor colorWithRed:235/255.0 green:235/255.0 blue:241/255.0 alpha:1];
    [self.view addSubview:table];
    //[self.view isLoading:YES];
}
//CommunityTableView自定义的代理方法
-(void)clickBtnAtIndex:(NSInteger)index
{
    NSLog(@"_______________________");
    
    if (index==1) {
        self.tabBarController.tabBar.hidden=YES;
        //进入贴吧界面
        TieBaViewController *vc=[[TieBaViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }else if (index==2){
        //互动界面
//        MessageListViewController *vc=[[MessageListViewController alloc]init];
//        //HuDongViewController *vc=[[HuDongViewController alloc]init];
//        [self.navigationController pushViewController:vc animated:YES];
        
        ZGWHuDongViewController *zgwHuDongVC = [[ZGWHuDongViewController alloc] init];
        [self.navigationController pushViewController:zgwHuDongVC animated:YES];
    }
    else if (index==9){
        CircleViewController *vc=[[CircleViewController alloc]init];
        vc.biaoqianState=1;
        self.tabBarController.tabBar.hidden=YES;
        [self.navigationController pushViewController:vc animated:YES];
    }else if (index==10){
        HotAndGreatViewController *vc=[[HotAndGreatViewController alloc]init];
        vc.myTitle=@"热门帖子";
        vc.selectedIndex=2;
        self.tabBarController.tabBar.hidden=YES;
        self.navigationController.navigationBar.hidden=NO;
        [self.navigationController pushViewController:vc animated:YES];
    }
}
//点击了热门话题的哪一个1，2，3，4
-(void)clickHotAtIndex:(NSInteger)index andBiaoQian:(NSString *)str andTagId:(NSString *)tagId
{
    TieZiViewController *vc=[[TieZiViewController alloc]init];
    self.navigationController.navigationBar.hidden=NO;
    self.tabBarController.tabBar.hidden=YES;
    vc.barState=1;
    vc.biaoti=str;
    vc.tagId=tagId;
    [self.navigationController pushViewController:vc animated:YES];
}
//点击用户头像
-(void)userHeadBtnClick:(NSInteger)useId
{
    SelfViewController *vc=[[SelfViewController alloc]init];
    self.tabBarController.tabBar.hidden=YES;
    vc.userId=useId;
    vc.barState=1;
    [self.navigationController pushViewController:vc animated:YES];
}

//更多标签按钮点击事件
-(void)moreBiaoQianBtnClick:(NSMutableArray *)arr
{
    BiaoQianViewController *vc=[[BiaoQianViewController alloc]init];
    self.navigationController.navigationBar.hidden=NO;
    self.tabBarController.tabBar.hidden=YES;
    vc.allBiaoQianArray=[NSMutableArray arrayWithArray:arr];
    [self.navigationController pushViewController:vc animated:YES];
}
//个性签名完整显示
-(void)allPersonalNameBtnClick:name
{
    PersonalNameViewController *vc=[[PersonalNameViewController alloc]init];
    vc.personalName=name;
    self.navigationController.navigationBar.hidden=NO;
    self.tabBarController.tabBar.hidden=YES;
    [self.navigationController pushViewController:vc animated:YES];
}

//帖子详情
-(void)gotoXiangQing:(NSString *)topicId
{
    TieBaXiangQingViewController *vc=[[TieBaXiangQingViewController alloc]init];
    //vc.arr=arr;
    vc.topic_id=[topicId integerValue];
    [self.navigationController pushViewController:vc animated:YES];
}


//进入用户详情界面
-(void)gotoMyAttentionViewController:(NSString *)userId
{
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    NSInteger currentUserId=[[user objectForKey:@"userId"] integerValue];
    NSInteger headUserId=[userId integerValue];
    if (currentUserId == headUserId) {
        SelfViewController *vc=[[SelfViewController alloc]init];
        self.tabBarController.tabBar.hidden=YES;
        vc.userId=headUserId;
        vc.barState=1;
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        //我关注的
        MyAttentionViewController *vc=[[MyAttentionViewController alloc]init];
        vc.barState=1;
        vc.userId=userId;
        [self.navigationController pushViewController:vc animated:YES];
    }
    
    
}


//获取数据是否成功
-(void)getDataSuccess:(BOOL)success
{
    if (!success) {
        [self.view showPromptMessage:true and:@"获取数据失败"];
        if (_myTimer==nil) {
             _myTimer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerRun) userInfo:nil repeats:YES];
        }
    }
}
//启动定时器
-(void)timerRun
{
    if (_myTime>=1) {
        [_myTimer invalidate];
        _myTimer=nil;
        _myTime=0;
        [self.view showPromptMessage:false and:nil];
    }
    _myTime++;
}
-(void)viewWillAppear:(BOOL)animated
{
    if (_myTime!=0) {
        [_myTimer  invalidate];
        _myTimer=nil;
        _myTime=0;
         [self.view showPromptMessage:false and:nil];
    }
    self.tabBarController.tabBar.hidden=NO;
    self.navigationController.navigationBar.hidden=YES;
    [self myClearCacheAction];
    if (!_gotoShowDaySignInViewController) {
        [self getSuperSignInHttpData];
    }else{
        //签到失败，开始准备后一天的签到
        NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
        NSString *lastSignTime=[user objectForKey:@"lastSignTime"];
        if (lastSignTime==nil) {
            return;
        }
        NSInteger days=[self getDays:lastSignTime];
        if (days>0) {
            [self getSuperSignInHttpData];
        }else{
            
        }

    }
}



-(void)myClearCacheAction{
    dispatch_async(
                   dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
                   , ^{
                       NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
                       
                       NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
                       NSLog(@"files :%lu",(unsigned long)[files count]);
                       for (NSString *p in files) {
                           NSError *error;
                           NSString *path = [cachPath stringByAppendingPathComponent:p];
                           if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
                               NSLog(@"开始清理缓存");
                               [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
                           }
                       }
                });
}



-(void)getSuperSignInHttpData
{
    AFHTTPRequestOperationManager * manager=[AFHTTPRequestOperationManager manager];
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.responseSerializer=[AFHTTPResponseSerializer serializer];
    
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    NSString *token= [user objectForKey:@"token"];
    
    [manager GET:[NSString stringWithFormat:@"%@%@",UserInfo,token] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"userInfo===%@",dic);
        if (dic) {
            if ([dic[@"last_sign"] isKindOfClass:[NSNull class]]) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    ShowDaySignInViewController *vc=[ShowDaySignInViewController new];
                    vc.days=[NSString stringWithFormat:@"%@",dic[@"all_sign"]];
                    vc.dontGotoShowDaySignInViewController=^(BOOL isGo){
                        _gotoShowDaySignInViewController=isGo;
                    };
                    [self.navigationController pushViewController:vc animated:YES];
                });
                
            }else{
                NSString *str=[NSString stringWithFormat:@"%@",dic[@"last_sign"]];
                NSInteger days=[self getDays:str];
                if (days>0) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        ShowDaySignInViewController *vc=[ShowDaySignInViewController new];
                        vc.days=[NSString stringWithFormat:@"%@",dic[@"all_sign"]];
                        vc.dontGotoShowDaySignInViewController=^(BOOL isGo){
                            _gotoShowDaySignInViewController=isGo;
                        };
                        [self.navigationController pushViewController:vc animated:YES];
                    });
                }else{
                    
                }
                
            }
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error.localizedDescription);
    }];
    
    
}

-(NSInteger)getDays:(NSString *)str
{
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSGregorianCalendar];
    [gregorian setFirstWeekday:2];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *fromDate;
    NSDate *toDate;
    [gregorian rangeOfUnit:NSDayCalendarUnit startDate:&fromDate interval:NULL forDate:[dateFormatter dateFromString:str]];
    [gregorian rangeOfUnit:NSDayCalendarUnit startDate:&toDate interval:NULL forDate:[NSDate date]];
    NSDateComponents *dayComponents = [gregorian components:NSDayCalendarUnit fromDate:fromDate toDate:toDate options:0];
    // dayComponents.day  即为间隔的天数
    NSLog(@"======%ld",dayComponents.day);
    return dayComponents.day;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
